<template>
  <div class="step1">
    <div class="step1-form">
      <BasicForm @register="register" />
    </div>

    <div>
      <a-table :columns="columns" :data-source="generatorConfig!.tableConfigs" :pagination="false">
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.key === 'order'">
            <span>
              {{ index + 1 }}
            </span>
          </template>
          <template v-if="column.key === 'isMain'">
            <span>
              <a-tag :color="record.isMain ? 'blue' : 'orange'">
                {{ record.isMain ? t('主表') : t('附表') }}
              </a-tag>
            </span>
          </template>
          <template v-else-if="column.key === 'relationField'">
            <template v-if="index > 0">
              <Select
                style="width: 200px"
                disabled
                v-model:value="record[column.key]"
                :placeholder="t('选择功能后自动带出')"
              >
                <SelectOption
                  v-for="(name, idx) in selectOptions[record.tableName]"
                  :key="idx"
                  :value="name"
                >
                  {{ name }}
                </SelectOption>
              </Select>
            </template>
          </template>
          <template v-else-if="column.key === 'relationTableField'">
            <template v-if="index > 0">
              <Select
                style="width: 200px"
                v-model:value="record[column.key]"
                :placeholder="t('选择功能后自动带出')"
                disabled
              >
                <SelectOption
                  v-for="(name, idx) in selectOptions[mainTableName]"
                  :key="idx"
                  :value="name"
                >
                  {{ name }}
                </SelectOption>
              </Select>
            </template>
          </template>
        </template>
      </a-table>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { getDatabaselinkMultiTableColumns } from '/@/api/system/databaselink';
  import { getAuthList } from '/@/api/system/authorize';

  import { computed, inject, nextTick, onMounted, Ref, ref } from 'vue';
  import { Select } from 'ant-design-vue';

  import { GeneratorConfig } from '/@/model/generator/generatorConfig';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { TableInfo, FieldInfo } from '/@/components/Designer';
  import { JavaTypeConvertTsType } from '/@/utils/helper/designHelper';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { getFormTemplate } from '/@/api/form/design';
  import { FormJson } from '/@/model/generator/codeGenerator';
  import { FormEventColumnConfig } from '/@/model/generator/formEventConfig';
  import { getCodeTemplateInfo } from '/@/api/system/generator';

  const { t } = useI18n();
  const SelectOption = Select.Option;

  const { notification } = useMessage();
  const generatorConfig = inject<GeneratorConfig>('generatorConfig');
  let widgetForm = inject<Ref<any>>('widgetForm');
  let designType = inject<Ref<string>>('designType');

  const dataAuthHelpMessage = `
      1.启用数据权限会判断主表是否包含RuleUserlD字段如果存在，则不进行表结构修改，如果不存在，则会对主表进行字段添加。
      2.RuleUserlD主要用来控制每一条记录的权限所属人新增时，默认将当前登录认作为权限所属人。
      3.在表单设计中会添加“批量设置权限所属人”功能启用后，拥有该按钮权限的人员可以设置每一条记录的权限所属人。
        `;

  const formSchema: FormSchema[] = [
    {
      field: 'funcType',
      label: t('功能类型'),
      required: true,
      component: 'Select',
      title: t('基本信息'),
      colProps: { span: 24 },
      componentProps: {
        placeholder: t('请选择功能类型'),
        options: [
          { label: '代码生成器页面', value: 0 },
          { label: '表单设计页面', value: 1 },
        ],
        onChange: (val: ChangeEvent) => {
          generatorConfig!.outputConfig!.funcType = Number(val);
          initForm();
        },
      },
    },
    {
      field: 'formObj',
      label: t('选择功能'),
      required: true,
      component: 'SelectForm',
      colProps: { span: 24 },
      componentProps: {
        placeholder: t('请选择功能'),
        suffix: 'ant-design:ellipsis-outlined',
        formType: generatorConfig!.outputConfig!.funcType,
        isSingle: true,
        getPopupContainer: () => document.body,
        onChange: (val) => {
          generatorConfig!.outputConfig!.formObj = {
            formName: val.formName,
            formId: val.key,
          };
          changeFuncName(val.key);
        },
      },
    },
    {
      field: 'createCode',
      label: t('生成代码'),
      component: 'Switch',
      required: false,
      colProps: { span: 24 },
      componentProps: {
        checkedValue: true,
        unCheckedValue: false,
        onChange: (val) => {
          generatorConfig!.outputConfig!.createCode = val;
        },
      },
      ifShow: () => {
        return generatorConfig!.outputConfig!.funcType === 1;
      },
    },
    {
      field: 'className',
      label: t('功能名称'),
      required: true,
      component: 'Input',
      colProps: { span: 12 },
      dynamicDisabled: () => {
        return generatorConfig!.outputConfig!.funcType === 0;
      },
      componentProps: {
        placeholder: t('选择功能后自动带出'),
        onChange: (val) => {
          generatorConfig!.outputConfig!.className = val.target.value;
        },
      },
      ifShow: () => {
        return (
          generatorConfig!.outputConfig!.funcType === 0 ||
          generatorConfig!.outputConfig!.createCode === true
        );
      },
    },
    {
      field: 'comment',
      label: t('功能描述'),
      required: true,
      component: 'Input',
      colProps: { span: 12 },
      componentProps: {
        placeholder: t('请输入功能描述'),
        onChange: (val) => {
          generatorConfig!.outputConfig!.comment = val.target.value;
        },
      },
      ifShow: () => {
        return (
          generatorConfig!.outputConfig!.funcType === 0 ||
          generatorConfig!.outputConfig!.createCode === true
        );
      },
    },
    {
      field: 'outputArea',
      label: t('功能模块'),
      component: 'DicSelect',
      required: true,
      componentProps: {
        placeholder: t('请选择功能模块'),
        itemId: '1419276800524423333',
        isDefaultValue: true,
        onChange: (_, obj) => {
          if (obj) {
            generatorConfig!.outputConfig!.outputArea = obj.id;
            generatorConfig!.outputConfig!.outputValue = obj.value;
          }
        },
      },
      colProps: { span: 12 },
      ifShow: () => {
        return (
          generatorConfig!.outputConfig!.funcType === 0 ||
          generatorConfig!.outputConfig!.createCode === true
        );
      },
    },
    {
      field: 'remarks',
      label: t('备注'),
      component: 'Input',
      required: false,
      colProps: { span: 12 },
      componentProps: {
        placeholder: t('请输入备注'),
        onChange: (val) => {
          generatorConfig!.outputConfig!.remarks = val.target.value;
        },
      },
      ifShow: () => {
        return (
          generatorConfig!.outputConfig!.funcType === 0 ||
          generatorConfig!.outputConfig!.createCode === true
        );
      },
    },
    {
      field: 'isDataAuth',
      label: t('数据权限'),
      component: 'Switch',
      required: false,
      colProps: { span: 12 },
      helpMessage: dataAuthHelpMessage,
      helpComponentProps: { maxWidth: '400px' },
      dynamicDisabled: true,
      componentProps: {
        checkedValue: true,
        unCheckedValue: false,
      },
    },
    {
      field: 'dataAuthList',
      label: t('权限选择'),
      component: 'ApiSelect',
      required: false,
      colProps: { span: 12 },
      componentProps: {
        mode: 'multiple',
        placeholder: t('选择功能后自动带出'),
        api: getAuthList,
        labelField: 'name',
        valueField: 'id',
        getPopupContainer: () => document.body,
      },
      dynamicDisabled: true,
    },

    {
      field: 'databaseId',
      label: t('数据库'),
      component: 'DbSelect',
      required: true,
      title: t('数据库信息'),
      colProps: { span: 24 },
      dynamicDisabled: true,
      componentProps: {
        placeholder: t('选择功能后自动带出'),
      },
    },
  ];

  const columns = [
    {
      title: t('序号'),
      dataIndex: 'order',
      key: 'order',
      width: 80,
      align: 'center',
    },
    {
      title: t('数据表类别'),
      dataIndex: 'isMain',
      key: 'isMain',
      width: 120,
    },
    {
      title: t('数据表名称'),
      dataIndex: 'tableName',
      key: 'tableName',
    },
    {
      title: t('关联字段'),
      dataIndex: 'relationField',
      key: 'relationField',
    },
    {
      title: t('关联表字段'),
      key: 'relationTableField',
      dataIndex: 'relationTableField',
    },
  ];

  const [register, { validate, setFieldsValue, clearValidate, updateSchema }] = useForm({
    labelWidth: 100,
    schemas: formSchema,
    showActionButtonGroup: false,
  });
  const selectOptions = ref({});
  const selectTableName = computed(() =>
    generatorConfig!.tableConfigs!.map((item) => item.tableName),
  );

  const mainTableName = computed(
    () => generatorConfig!.tableConfigs!.find((item) => item.isMain)!.tableName,
  );

  defineEmits(['register']);

  const tableInfo = inject<Ref<TableInfo[]>>('tableInfo', ref([]));

  onMounted(() => {
    const { tableConfigs, databaseId, outputConfig } = generatorConfig!;

    setFieldsValue({
      funcType: outputConfig?.funcType,
      formObj: outputConfig?.formObj,
      className: outputConfig?.className,
      comment: outputConfig?.comment,
      outputArea: outputConfig?.outputArea,
      databaseId: databaseId,
      isDataAuth: outputConfig?.isDataAuth || false,
      dataAuthList: outputConfig?.dataAuthList || [],
      remarks: outputConfig?.remarks,
      createCode: outputConfig?.createCode || false,
    });

    setDatabase(tableConfigs, databaseId);
    nextTick(() => {
      clearValidate();
    });
  });
  function setDatabase(tableConfigs, databaseId) {
    if (tableConfigs && tableConfigs.length > 0) {
      getDatabaselinkMultiTableColumns({
        id: databaseId,
        tableNames: selectTableName.value.join(','),
      }).then((result) => {
        for (const key in result) {
          const columnInfo = result[key];
          //如果已经写入过的表格 不再添加
          if (!tableInfo?.value.find((x) => x.name === key)) {
            const fields = columnInfo.map((field) => {
              const filedInfo: FieldInfo = {
                name: field.column,
                length: field.dataLength,
                type: JavaTypeConvertTsType(field.dataType),
                isPk: field.primaryKey,
                isNullable: field.nullable,
              };
              return filedInfo;
            });

            tableInfo?.value.push({
              name: key,
              isMain: generatorConfig!.tableConfigs!.find((x) => x.tableName === key)
                ?.isMain as boolean,
              fields: fields,
            });
          }

          selectOptions.value[key] = columnInfo.map((x) => x.column);
        }
      });
    }
  }

  async function changeFuncName(id) {
    let res: any = {};
    let formJson: any = {};
    let isDataAuth = false;
    let dataAuthList = [];
    if (generatorConfig!.outputConfig!.funcType === 1) {
      res = await getFormTemplate(id);
      formJson = JSON.parse(res.formJson);
      generatorConfig!.formId = id;
      isDataAuth = formJson.isDataAuth;
      dataAuthList = formJson.dataAuthList;
    } else {
      res = await getCodeTemplateInfo(id);
      formJson = JSON.parse(res.content);
      isDataAuth = formJson.outputConfig.isDataAuth;
      dataAuthList = formJson.outputConfig.dataAuthList;
      generatorConfig!.formId = res.formId;
    }

    setFieldsValue({
      className: generatorConfig!.outputConfig!.funcType === 1 ? undefined : res.name,
      comment:
        generatorConfig!.outputConfig!.funcType === 1 ? res.remark : formJson.outputConfig?.comment,
      outputArea: formJson.outputConfig?.outputArea,
      databaseId: formJson.databaseId,
      isDataAuth: isDataAuth,
      dataAuthList: dataAuthList,
    });

    generatorConfig!.databaseId = formJson.databaseId;
    generatorConfig!.formJson = formJson.formJson;
    generatorConfig!.tableConfigs = formJson.tableConfigs || formJson.tableStructureConfigs;
    generatorConfig!.tableStructureConfigs = formJson.tableStructureConfigs;
    generatorConfig!.formEventConfig = formJson.formEventConfig;
    if (generatorConfig!.outputConfig!.funcType !== 1) {
      generatorConfig!.listConfig = formJson.listConfig;
      let filterBtn = [
        'batchdelete',
        'batchSetUserId',
        'import',
        'export',
        'print',
        'templateprint',
      ];
      generatorConfig!.listConfig.buttonConfigs = formJson.listConfig.buttonConfigs.filter((o) => {
        return !filterBtn.includes(o.code);
      });
    }

    generatorConfig!.outputConfig.dataAuthList = dataAuthList;
    generatorConfig!.outputConfig.isDataAuth = isDataAuth;
    generatorConfig!.outputConfig.className =
      generatorConfig!.outputConfig!.funcType === 1 ? undefined : res.name;
    generatorConfig!.outputConfig.comment =
      generatorConfig!.outputConfig!.funcType === 1 ? res.remark : formJson.outputConfig?.comment;
    generatorConfig!.formJson.list = generatorConfig!.formJson.list.filter(
      (x) => x.type !== 'hiddenComponent' && x.type !== 'button',
    );
    setDatabase(formJson.tableConfigs, formJson.databaseId);
    widgetForm!.value = generatorConfig!.formJson;
    let type = generatorConfig!.outputConfig!.funcType === 1 ? 'formDesignType' : 'type';
    designType!.value = res[type] == 2 ? 'template' : res[type] == 1 ? 'code' : 'data';
  }
  function initForm() {
    updateSchema([
      {
        field: 'formObj',
        componentProps: {
          formType: generatorConfig!.outputConfig!.funcType,
        },
      },
      {
        field: 'className',
        componentProps: {
          placeholder:
            generatorConfig!.outputConfig!.funcType === 1
              ? t('请输入功能名称')
              : t('选择功能后自动带出'),
        },
      },
    ]);
    setFieldsValue({
      formObj: null,
      className: undefined,
      comment: '',
      outputArea: null,
      databaseId: null,
      isDataAuth: false,
      dataAuthList: [],
    });
    clearValidate();
    generatorConfig!.databaseId = '';
    generatorConfig!.formJson = {} as FormJson;
    generatorConfig!.tableConfigs = [];
    generatorConfig!.tableStructureConfigs = [];
    generatorConfig!.formEventConfig = {} as FormEventColumnConfig;
    generatorConfig!.outputConfig.dataAuthList = [];
    generatorConfig!.outputConfig.isDataAuth = false;
    generatorConfig!.outputConfig.className = undefined;
    widgetForm!.value = generatorConfig!.formJson;
  }
  //验证当前步骤的数据
  const validateStep = async (): Promise<boolean> => {
    try {
      await validate();
      const { tableConfigs, outputConfig } = generatorConfig as GeneratorConfig;

      //判断tableconfig 是否为空 或者 一条数据都没有
      if ((designType!.value == 'data' && !tableConfigs) || tableConfigs!.length === 0) {
        notification.error({
          message: t('提示'),
          description: t('数据表配置不能为空！'),
        }); //提示消息
        return false;
      }
      console.log(outputConfig, 'outputConfig');
      if (!/^[a-zA-Z][a-zA-Z0-9]*$/.test(outputConfig.className!)) {
        notification.error({
          message: t('提示'),
          description: t('功能名称只能是数字和字母组成，必须以英文字母开头'),
        }); //提示消息
        return false;
      }

      for (const config of tableConfigs!) {
        //如果是主表 可以不需要关联字段等
        if (config.isMain) {
          if (!config.tableName) {
            notification.error({
              message: t('提示'),
              description: t('主表表名未能配置成功！'),
            }); //提示消息
            return false;
          }
        } else {
          //子表需要验证关联字段 已经关联表 是否选择好
          if (!config.tableName) {
            notification.error({
              message: t('提示'),
              description: t('子表表名未能配置成功！'),
            }); //提示消息
            return false;
          }

          if (!config.relationField) {
            notification.error({
              message: t('提示'),
              description: t(`{name} 表 关联字段未选中`, { name: config.tableName }),
            }); //提示消息
            return false;
          }

          if (!config.relationTableField) {
            notification.error({
              message: t('提示'),
              description: t(`{name} 表 关联表字段未选中`, { name: config.tableName }),
            }); //提示消息
            return false;
          }
        }
      }
    } catch (error) {
      return false;
    }
    return true;
  };

  defineExpose({ validateStep, setFieldsValue });
</script>
<style lang="less" scoped>
  .step1 {
    h3 {
      margin: 0 0 12px;
      font-size: 16px;
      line-height: 32px;
      color: @text-color;
    }

    h4 {
      margin: 0 0 4px;
      font-size: 14px;
      line-height: 22px;
      color: @text-color;
    }

    p {
      color: @text-color;
    }
  }

  .pay-select {
    width: 20%;
  }

  .pay-input {
    width: 70%;
  }

  :deep(.ant-tag-orange),
  :deep(.ant-tag-blue) {
    background: #fff;
    padding: 3px 12px;
    font-size: 13px;
  }

  :deep(.ant-tooltip-inner) {
    white-space: pre-wrap !important;
  }

  :deep(.ant-table-tbody > tr > td) {
    padding: 16px 8px;
  }
</style>
